package sso.client2.filter;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sso.client2.utils.HttpClientUtil;
import sso.client2.utils.StringUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@SuppressWarnings("all")
public class SSOClientFilter implements Filter {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private String ssoServer = "http://localhost:8080";

	private String checkUrl = ssoServer + "/auth/checkLogin";
	private String validateTicketUrl = ssoServer + "/ticket/verify";
	private String localExitUrl = "/logout";
	private String needLoginUrls = "/index";// 登录拦截的url，使用逗号分隔


	@Override
	public void destroy() {
		System.out.println("ssoClientFilter is destroy");
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		HttpSession session = request.getSession();
		String username = (String) session.getAttribute("username");
		String ticket = request.getParameter("ticket");
		String globalSessionId = request.getParameter("globalSessionId");
		String url = request.getRequestURL().toString();

		String[] needLoginAry = needLoginUrls.split(",");

		// 除了包含needLoginAry的请求，其他的都不拦截
		if (needLoginAry != null && needLoginAry.length > 0) {
			boolean contains = false;
			for (String str : needLoginAry) {
				if (url.contains(str)) {
					contains = true;
					break;
				}
			}
			if (!contains) {
				logger.info("{}不包含隐私内容，无需SSO拦截",url);
				filterChain.doFilter(request, response);
				return;
			}
		}
		// 登录拦截
		if (StringUtil.isEmpty(username)) {// 本地未登录
			// 中心已经登录
			if (!StringUtil.isEmpty(ticket)) {
				if (!StringUtil.isEmpty(globalSessionId)) {
					// 令牌验证
					// 发送请求参数
					String basePath = request.getScheme() + "://" + request.getServerName() + ":"
							+ request.getServerPort() + request.getContextPath() + "/";
					Map<String, String> postPara = new HashMap<>();
					postPara.put("ticket",ticket);
					postPara.put("globalSessionId",globalSessionId);
					postPara.put("localLoginOutUrl",basePath + localExitUrl);
					postPara.put("localSessionId",session.getId());

					JSONObject jsonObject = HttpClientUtil.sendPost(validateTicketUrl, JSON.toJSONString(postPara));
					if(jsonObject != null){
						int code = Integer.parseInt(jsonObject.get("code").toString());
						if (code == 0) {
							username = (String) jsonObject.get("account");
							session.setAttribute("username", username);
							session.setAttribute("globalSessionId", globalSessionId);// 等退出全局登录时使用
							filterChain.doFilter(request, response);
							logger.info("验票成功");
							return;
						} else {
							logger.info("验票失败，重新跳转到sso登录页面");
							response.sendRedirect(checkUrl + "?service=" + url);
						}
					}else {
						logger.info("验票失败，重新跳转到sso登录页面");
						response.sendRedirect(checkUrl + "?service=" + url);
					}
				} else {
					logger.info("globalSessionId为空！");
				}
			} else {
				logger.info("ticket为空！跳转到认证中心登录页");
				response.sendRedirect(checkUrl + "?service=" + url);
			}
		} else {// 已经登录
			logger.info("已经登录，无需拦截,进入系统:" + request.getContextPath());
			filterChain.doFilter(request, response);
			return;
		}

	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("ssoClientFilter is init");
	}
}